import { getSetting, chooseAddress, openSetting, showModal, showToast } from '../../utils/asyncWx.js'
// import regeneratorRuntime from '../../lib/runtime';

Page({
  data: {
    address: {},
    cate: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },
  //生命周期
  onShow() {
    //1.获取缓存中的收货地址信息
    const address = wx.getStorageSync("address");
    //获取缓存中的购物车数据
    const cart = wx.getStorageSync("cart") || []
    this.setData({ address });
    this.setCart(cart);
  },

  //点击收货地址
  async handleChooseAddress() {
    try {
      //1.获取 权限状态
      const res1 = await getSetting();
      //获取权限状态，主要发现一些 属性名 很怪异 的时候，都要使用[]形式来获取属性值
      const scopeAddress = res1.authSetting["scope.address"];
      //2.判断权限状态
      if (scopeAddress === false) {
        //4. 诱导用户打开 授权页面
        await openSetting();
      }
      //5. 调用收货地址的 api
      let address = await chooseAddress();
      address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;
      //存入到缓存中
      wx.setStorageSync("address", address)

    } catch (error) {
      console.log(error);
    }

  },

  //商品的选中
  handleItemChange(e) {
    //1.获取被修改商品的id
    const goods_id = e.currentTarget.dataset.id
    //2.获取购物车数组
    let { cart } = this.data;
    //3.找到被修改的商品对象
    let index = cart.findIndex(v => v.goods_id === goods_id);
    //4.选中状态取反
    cart[index].checked = !cart[index].checked;
    this.setCart(cart);

  },

  //设置购物车状态，同时重新计算 底部工具栏的数据 全选 总价格 总数量
  setCart(cart) {
    let allChecked = true;
    //1.总价格、总数量
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      if (v.checked) {
        totalPrice += v.num * v.goods_price;
        totalNum += v.num;
      } else {
        allChecked = false;
      }
    })
    //判断cart是否为空
    allChecked = cart.length != 0 ? allChecked : false;

    //5,6把购物车数据重新设置回data和缓存中
    this.setData({
      cart, totalPrice, totalNum, allChecked
    });
    wx.setStorageSync("cart", cart);
  },

  //商品全选功能
  handleItemAllCheck() {
    //1.获取data中的数据
    let { cart, allChecked } = this.data;
    //2.修改值
    allChecked = !allChecked;
    //3.循环修改cart数组中商品的选中状态
    cart.forEach(v => v.checked = allChecked);
    //4.把修改后的值，填充会data或缓存中
    this.setCart(cart);
  },

  //商品数量的编辑功能
  async handleItemNumEdit(e) {
    //1.获取传递过来的参数
    const { operation, id } = e.currentTarget.dataset;
    //2.获取购物车数组
    let { cart } = this.data;
    //3.找到需要修改的商品的索引
    const index = cart.findIndex(v => v.goods_id === id);
    //判断是否要执行删除
    if (cart[index].num === 1 && operation === -1) {
      //弹窗提示
      //好像async没用，所以这里保留了繁琐的写法
      wx.showModal({
        title: '提示',
        content: '是否要删除',
        success: (res) => {
          if (res.confirm) {
            cart.splice(index, 1);
            this.setCart(cart);
          } else {
          }
        }
      })
      //下面这是async的写法
      // const res = await showModal({content:"是否要删除？"});
      // if (res.confirm) {
      //   cart.splice(index, 1);
      //   this.setCart(cart);
      // }

    } else {
      //4.进行数量修改
      cart[index].num += operation;
      //5.设置回data和缓存中
      this.setCart(cart);
    }

  },

  //点击 结算
  async handlePay() {
    //1.判断收货地址
    const { address, totalNum } = this.data;
    if (!address.userName) {
      await showToast({ title: "您还没有选择收货地址" });
      return
    }
    //2.判断用户有没有选购商品
    if (totalNum === 0) {
      await showToast({ title: "您还没有选购商品" });
      return
    }
    //跳转到支付页面
    wx.navigateTo({
      url: "/pages/pay/index"
    });
  }
})

/**
   //1.获取 权限状态
   wx.getSetting({
     success: (result) => {
       //2.获取权限状态，主要发现一些 属性名 很怪异 的时候，都要使用[]形式来获取属性值
       const scopeAddress = result.authSetting["scope.address"];
       if (scopeAddress === true || scopeAddress === undefined) {
         wx.chooseAddress({
           success: (result1) => {
             console.log(result1);
           }
         });
       } else {
         //3.用户 以前拒绝过授予权限 先诱导用户打开授权页面
         wx.openSetting({
           success: (result2) => {
             //4.可以调用收货地址代码
             wx.chooseAddress({
               success: (result3) => {
                 console.log(result3);
               }
             });
           }
         })
       }
     }
   });
   */
